package UDPEcho;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPEchoSever3 {
    DatagramSocket socket = null;
    public UDPEchoSever3(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动！！！");
        while(true) {
            //接收客户端发来的数据报
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(requestPacket);
            //根据请求返回响应
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            String response = process(request);
            //将响应返回给客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length, requestPacket.getSocketAddress());
            socket.send(responsePacket);
            //打印日志
            System.out.printf("[%s:%d],req:%s,req:%s\n", requestPacket.getSocketAddress(), requestPacket.getPort(), request, response);
        }
    }

    private String process(String request) {
    return request;
    }

    public static void main(String[] args) throws IOException {
        UDPEchoSever3 udpEchoSever3 = new UDPEchoSever3(2200);
        udpEchoSever3.start();
    }
}
